<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>上传Excel文档</title>
  </head>
  <body>
    <input id="excel-file-input" type="file" name="file" accept=".xls, .xlsx" />
    <button type="submit" id="upload-button">上传Excel文档</button>

    <button id="download-button">下载</button>

    <script>
      document.getElementById("upload-button").addEventListener("click", async () => {
        const fileInput = document.getElementById("excel-file-input");
        const file = fileInput.files[0];

        if (!file) {
          alert("Please select an Excel file to upload.");
          return;
        }

        const formData = new FormData();
        formData.append("file", file);

        try {
          const response = await fetch("/api/upload", {
            method: "POST",
            body: formData,
          });

          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          const data = await response.json();
          console.log("File uploaded successfully:", data.filePath);
          // 在这里可以处理服务器返回的filePath或其他信息
        } catch (error) {
          console.error("Error uploading file:", error);
        }
      });

      document.getElementById("download-button").addEventListener("click", async () => {
        try {
          const url = "/api/download";
          const params = {
            filename: "20240320_223156-客户表.xls",
          };

          // 将参数转换为查询字符串
          let queryString = Object.keys(params)
            .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
            .join("&");

          // 将查询字符串附加到URL后面
          const finalUrl = `${url}?${queryString}`;

          const response = await fetch(finalUrl, {
            method: "GET",
          });

          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }

          const data = await response.json();
          downloadFile(data.url);
          // console.log("File uploaded successfully:", data.filePath);
          // 在这里可以处理服务器返回的filePath或其他信息
        } catch (error) {
          console.error("Error uploading file:", error);
        }
      });

      const downloadFile = (fileUrl) => {
        var link = document.createElement("a");
        link.style.display = "none"; // 隐藏链接元素
        link.href = fileUrl;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      };
    </script>
  </body>
</html>
